<script setup>
import {ref, onMounted, watch} from "vue";
import {getChapterInfoReq} from "@/api/chapter.js";
import {useRoute, useRouter} from "vue-router";
import {ElLoading, ElMessage} from 'element-plus';
import {addFicReq, getCategoryReq, getFictionReq} from "@/api/fiction.js";

const info = ref({
    title: '',
    coverImage: "",
    introduction: '',
    author: '',
    latestChapterTitle: '',
    latestChapterUrl: '',
    latestTime: '',
    chapters: [],
    categoryId:''
});
//小说表单
const fictionModel=ref({
    title:'',
    categoryId:'',
    coverImage:'',
    author:'',
    introduction:'',
    id:'',
    titleUrl:''
})

const router = useRouter();
const route = useRoute();
const loadingInstance = ref(null);//加载

//弹窗显示状态
const dialogFormVisible = ref(false)
//弹窗标题
const title = ref('选择小说分类')

//分页
const page = ref({
    pageNum: 1,
    pageSize: 32,
    total: 0
});

const paginatedChapters = ref([]);

const titleUrl = ref('');

const categories = ref()

//显示弹窗
const showDialog = () => {
    dialogFormVisible.value = true;
    getCategories();
}

//获取小说分类
const getCategories = async () => {
    //获取小说分类
    let cresult = await getCategoryReq()
    categories.value=cresult.data

    console.log(cresult.data);
}

//获取小说详情（章节信息等）
const fetchChapterInfo = async (baseUrl) => {
    loadingInstance.value = ElLoading.service({fullscreen: true, text: '加载中...'});

    try {
        const response = await getChapterInfoReq(baseUrl);
        info.value = response.data;
        page.value.total = info.value.chapters.length;
        paginateChapters();
    } catch (error) {
        console.error('请求失败:', error);
    } finally {
        loadingInstance.value.close();
    }
};

//添加小说
const addFicion = async () => {
    fictionModel.value.title = info.value.title
    fictionModel.value.coverImage = info.value.coverImage
    fictionModel.value.introduction = info.value.introduction
    fictionModel.value.categoryId = info.value.categoryId
    fictionModel.value.titleUrl = titleUrl;
    let str = info.value.author.split('：');
    fictionModel.value.author = str[1]

    let result = await addFicReq(fictionModel.value);
    ElMessage.success(result.message)
    //关闭弹窗
    dialogFormVisible.value = false;
}

//分页计算逻辑
const paginateChapters = () => {
    const start = (page.value.pageNum - 1) * page.value.pageSize;
    const end = start + page.value.pageSize;
    paginatedChapters.value = info.value.chapters.slice(start, end);
};

//跳转到文章页面，展示文章
const showContent = (url) => {
    router.push({path: `/webShowFiction`, query: {url: url}});
};

//分页更新页码操作
const handleSizeChange = (size) => {
    page.value.pageSize = size;
    page.value.pageNum = 1;
    paginateChapters();
};
const handleCurrentChange = (num) => {
    page.value.pageNum = num;
    paginateChapters();
};

//监视路由变化
watch(route, () => {
    titleUrl.value = route.query.titleUrl || '';
    if (titleUrl.value) {
        fetchChapterInfo(titleUrl.value);
    }
}, {immediate: true});
</script>


<template>
    <el-card class="card-container">
        <template #header>
            <div class="card-header">
                <div class="image-container">
                    <el-image class="coverImage" :src='info.coverImage' fit="cover"></el-image>
                </div>
                <div class="text-container">
                    <el-descriptions :title="info.title">
                        <el-descriptions-item :label="info.author"/>
                        <el-descriptions-item label="最新章节：">
                            <template #default>
                                <a href="javascript:void(0)" @click="showContent(info.latestChapterUrl)">
                                    {{ info.latestChapterTitle }}
                                </a>
                            </template>
                        </el-descriptions-item>
                        <el-descriptions-item :label="info.latestTime"/>
                        <el-descriptions-item :label="info.introduction"/>
                    </el-descriptions>
                    <el-button id="submitBtn" type="primary" @click="showDialog">加入书库</el-button>
                </div>
            </div>
        </template>

        <!-- 将表格分成4列 -->
        <div class="chapter-grid">
            <div v-for="(chapter, index) in paginatedChapters" :key="index" class="chapter-item">
                <a href="javascript:void(0)" @click="() => showContent(chapter.url)">
                    {{ chapter.name }}
                </a>
            </div>
        </div>

        <el-pagination
            v-model:current-page="page.pageNum"
            v-model:page-size="page.pageSize"
            :page-sizes="[32, 40, 60, 80]"
            layout="sizes, prev, pager, next"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />

        <!-- 1.弹窗的显示需要控制
             2.分类表单内容form需要定义
             3.添加动作需要发送请求
        -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="500">
            <el-form ref="formRef" :rules="rules">
                <el-form-item label="小说分类">
                    <!--        选择分类下拉框-->
                    <el-select v-model="info.categoryId" placeholder="请选择分类">
                        <el-option v-for="item in categories" :key="item.id" :label="item.categoryName" :value="item.id"/>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addFicion()"> <!---->
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </el-card>
</template>

<style scoped>
.card-header {
    display: flex;
    align-items: center;
    height: auto;
    box-sizing: border-box;
}

.image-container {
    flex: 0 0 20%; /* 固定宽度为总宽度的30% */
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.coverImage {
    width: auto;
    max-height: 200px; /* 确保图片不会超过容器高度 */
    background-size: cover;
}

.text-container {
    flex: 0 0 70%; /* 固定宽度为总宽度的70% */
}

.chapter-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 四列布局 */
    gap: 10px; /* 间距 */
}

.chapter-item {
    text-align: center;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: #f9f9f9;
}

.chapter-item a {
    text-decoration: none;
    color: #409EFF;
}

.chapter-item a:hover {
    text-decoration: underline;
}
#submitBtn {
    float: right;
}
</style>
